package com.bristua.mall.common.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author hrt
 * @date 2018年1月4日
 * @description
 * 常用工具类
 */
public class Utils {

	/**
	 * 手机号码正则表达式
	 */
	private static final String PHONE_NUMBER_REG = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";

	/**
	 * 生成订单号时间戳+随机数组合
	 * @return
	 */
	public static String getOrdNo(){
		Random random = new Random();
		int x = random.nextInt(8999);
		int y = x + 1000;
		return DateUtils.getTimeStamp() + String.valueOf(y);
	}

	/**
	 * 相除
	 * @param obj 被除数，原有金额
	 * @param divisor 除数
	 * @return
	 */
	public static double divide(Object obj, int divisor){
		if(StringUtils.isEmpty(obj) || "0".equals(obj)){
			return 0;
		}
		BigDecimal bdAmt = new BigDecimal(String.valueOf(obj));
		BigDecimal bdAmt2 = new BigDecimal(String.valueOf(divisor));
		BigDecimal surplus= bdAmt.divide(bdAmt2);
		return surplus.doubleValue();
	}

	/**
	 * 相乘
	 * @param obj 被乘数，原有金额
	 * @param divisor 乘数
	 * @return
	 */
	public static double multiply(Object obj, int divisor){
		if(StringUtils.isEmpty(obj) || "0".equals(obj)){
			return 0;
		}
		BigDecimal bdAmt = new BigDecimal(String.valueOf(obj));
		BigDecimal bdAmt2 = new BigDecimal(String.valueOf(divisor));
		BigDecimal surplus= bdAmt.multiply(bdAmt2);
		return surplus.doubleValue();
	}


	/**
	 * 获取uuid
	 * @return
	 */
	public static String uuid(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 判断是否为手机号
	 * @param mobile
	 * @return
	 */
	public static boolean isMobile(String mobile){
        return valid(PHONE_NUMBER_REG, mobile);
	}

	/**
	 * 正则验证
	 * @param reg
	 * @param tmp
	 * @return
	 */
	public static boolean valid(String reg, String tmp){
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(tmp);
        return m.matches();
	}

	/**
	 * 获取请求流水
	 * @return
	 */
	public static String getRequestjournal(){
		return Long.toString(Math.abs(new Random().nextLong()));
	}

	/**
	 * 获取客户端真实IP
	 * @param request
	 * @return
	 */
	public static String getClientIp(HttpServletRequest request) {

		if (request == null)
			return null;
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("HTTP_CLIENT_IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();
		if(ip.indexOf(",") != -1){
			ip = ip.split(",")[0].toString() ;
		}
		if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)){
			try {
				ip = InetAddress.getLocalHost().getHostAddress();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}
		return ip;
	}

	/**
	 * 判断是不是微信浏览器打开的
	 * @param request
	 * @return
	 */
	public static boolean isWxBrowser(HttpServletRequest request) {

		String userAgent = request.getHeader("user-agent").toLowerCase();
		return userAgent.contains("micromessenger");
	}

	/**
	 * 获取完整的应用部署路径：例如：http://www.yidianlife.cn/mobile
	 * @param request
	 * @return
	 */
	public static String getAppUrl(HttpServletRequest request) {
		String url = request.getScheme() + "://" + request.getServerName();
		if(request.getServerPort() != 80
				&& request.getServerPort() != 443){
			url += ":" + request.getServerPort();
		}
		url += request.getContextPath();
		return url;
	}
	/**
	 * yyyyMMddHHmmssSSS+随机数组合
	 * @return  20位
	 */
	public static String genID(){
		Random random = new Random();
		int x = random.nextInt(89999);
		int y = x+10000;
		return "WX"+(String.valueOf(DateUtils.format(new Date(), "yyMMddHHmmssSSS"))+String.valueOf(y));
	}

    public static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
